<template>
	<view class="lease-goods-return">
		<!-- Goods -->
		<view class="container">
			<lease-order-goods :image="goods.image">
				<template #name>{{ goods.goods_name }}</template>
				<template #specs>
					{{ goods.spec_value_str }}，
					{{ goods.periods }}{{ getPeriodsUnit(goods.periods_attribute) }}
				</template>
				<template #price>
					<price :content="priceDayRent" mainSize="38rpx" minorSize="24rpx" color="#333333" :isPrefix="true"
						:isSuffix="true" />
					<text>（x{{ goods.periods }}期）</text>
				</template>
			</lease-order-goods>
		</view>

		<!-- Price -->
		<view class="container mt20">
			<view class="price-item">
				<view class="price-name" @tap="isShowRendPriceUnreturnModal = true">
					<text>往期未还金额</text>
					<u-icon class="ml10" name="question-circle" color="#999999" />
				</view>
				<view class="price-count">¥{{ pricePayable }}</view>
			</view>
			<view class="price-item">
				<view class="price-name" @tap="isShowPriceLateFeeModal = true">
					<text>逾期滞纳金</text>
					<u-icon class="ml10" name="question-circle" color="#999999" />
				</view>
				<view class="price-count ornament">+¥{{ priceLateFee }}</view>
			</view>
			<view class="price-item">
				<view class="price-name" @tap="isShowFalsifyPriceModal = true">
					<text>违约金</text>
					<u-icon class="ml10" name="question-circle" color="#999999" />
				</view>
				<view class="price-count ornament">+¥{{ billInfo.falsify_price }}</view>
			</view>
			<view class="price-total">
				<view class="price-total-title">应还</view>
				<view class="price-total-count">¥{{ priceTotalRent }}</view>
			</view>
		</view>

		<!-- Pay -->
		<view class="container mt20">
			<view class="payway-title">支付方式</view>
			<u-radio-group v-model="payway" @change="radioGroupChangePayway" style="width: 100%;">
				<view class="payway-content">
					<block v-for="(item, index) in paywayList" :key="item.id">
						<view class="payway-item" @tap="onPayway(item)">
							<view class="row">
								<u-icon :name="item.icon" width="48" height="48" />
								<view class="ml20">
									<view class="payway-name">{{ item.name }}</view>
									<view class="payway-extra">{{ item.extra }}</view>
								</view>
							</view>
							<u-radio class="payway-radio" :name="item.pay_way" />
						</view>
					</block>
				</view>
			</u-radio-group>
		</view>


		<!-- Agree -->
<!-- 		<view class="mt20">
			<u-checkbox v-model="isAgree" shape="circle">
				<text class="sm lighter">已阅读并同意</text>
				<text class="sm primary">《租赁合同》</text>
			</u-checkbox>
		</view> -->

		<!-- Submit -->
		<view class="fixed">
			<view class="button--submit" @tap="onSubmit">确认并支付</view>
		</view>

		<!-- 往期未还金额 说明 -->
		<u-modal v-model="isShowRendPriceUnreturnModal" title="说明" confirm-text="我知道了">
			<view class="desc-container">
				<text class="desc-title">往期未还金额：</text>
				<text>是指您往期（包含本期）超时未还的账单累计总金额，可在还款账单中查看明细</text>
			</view>
		</u-modal>

		<!-- 逾期滞纳金 说明 -->
		<u-modal v-model="isShowPriceLateFeeModal" title="说明" confirm-text="我知道了">
			<view class="desc-container">
				<text class="desc-title">逾期滞纳金：</text>
				<text>是指您上期超时未还的账单累计到下个月；如未一直还款，将按天数来算逾期滞纳金，请留意您的账单</text>
				<!-- <text>费率=本金 x 0.1%/天</text> -->
			</view>
		</u-modal>

		<!-- 违约金 说明 -->
		<u-modal v-model="isShowFalsifyPriceModal" title="说明" confirm-text="我知道了">
			<view class="desc-container">
				<text class="desc-title">违约金：</text>
				<text>您当前租期未到期，提前还机需支付相应的违约金</text>
			</view>
		</u-modal>


		<!-- 支付密码 -->
		<set-pay-pwd ref="setPayPwd" @confirm="handlePayOrder" />
	</view>
</template>


<script>
	import {
		leaseReturnBill,
		payment
	} from '@/api/lease'

	import {
		prepay,
		getAlipayPayStatus
	} from '@/api/app'
	import {
		wxpay,
		alipay
	} from '@/utils/pay'

	export default {
		data() {
			return {
				order_id: '', // 订单ID
				payway: 1, // 支付方式
				paywayList: [], // 支付方式列表
				goods: {}, // 商品信息
				billInfo: {}, // 账单信息

				priceDayRent: 0, // 商品每天的租金

				pricePayable: 0, // 应还
				priceLateFee: 0, // 总滞纳金
				priceTotalRent: 0, // 往期未还金额

				// isAgree: false, // 同意合同

				isShowPriceLateFeeModal: false, // 滞纳金Desc
				isShowFalsifyPriceModal: false, // 违约金Desc
				isShowRendPriceUnreturnModal: false, // 往期未还Desc
			}
		},

		methods: {
			// 输出分期单位
			getPeriodsUnit(value) {
				switch (value) {
					case 'is_week':
						return '周';
					case 'is_month':
						return '个月';
				}
			},

			// 选择支付方式
			radioGroupChangePayway(value) {
				console.log(value);
			},

			// 选择支付方式
			onPayway(item) {
				this.payway = item.pay_way;
			},

			// 点击提交
			onSubmit() {
				// if (!this.isAgree) return uni.showToast({
				// 	title: '请先阅读租赁合同',
				// 	icon: 'none'
				// });
				const payway = this.payway;
				if (payway == 3) {
					this.$refs.setPayPwd.hasPayWord().then(res => {
						this.$refs.setPayPwd.showInputPwd();
					});
				} else {
					this.handlePayOrder();
				}
			},

			handlePayOrder(password) {
				const payway = this.payway;
				uni.showLoading({
					title: '支付中...',
					mask: true
				});
				leaseReturnBill({
					id: this.order_id,
					action: 'submit',
					pay_way: payway,
					pay_password: password
				}).then(res => {

					if (res.code != 1) return;
					this.$refs.setPayPwd.showConfirm = false;

					const data = res.data;
					prepay({
						from: data.from,
						order_id: data.order_id
					}).then(res => {
						const code = res.code;
						const data = res.data;

						switch (code) {
							case 1:
								this.handleWeChat(data);
								break;
							case 20001:
								this.handleAlipay(data);
								break;
							case 10001:
								uni.redirectTo({
									url: `/bundle/pages/lease_return_pay_result/lease_return_pay_result?id=${this.billInfo.id}`
								})
								break;
						}
					});

				}).catch(() => {
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}).finally(() => {
					setTimeout(() => uni.hideLoading(), 500);
				});
			},

			// 微信支付
			handleWeChat(data) {
				wxpay(data).then(res => {
					if (res == 'success') {
						uni.redirectTo({
							url: `/bundle/pages/lease_return_pay_result/lease_return_pay_result?id=${this.billInfo.id}`
						})
					} else {
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
			},

			// 支付宝支付
			handleAlipay(data) {
				// #ifdef H5
				alipay(data);
				// #endif

				// #ifdef MP-ALIPAY
				const tradeNo = data?.data?.trade_no;
				my.tradePay({
					tradeNO: tradeNo,
					success: (res) => {
						getAlipayPayStatus({
							trade_no: tradeNo
						}).then(res => {
							if (res.tradeStatus == 'TRADE_SUCCESS') {
								uni.redirectTo({
									url: `/bundle/pages/lease_return_pay_result/lease_return_pay_result?id=${this.billInfo.id}`
								})
							} else {
								uni.showToast({
									title: '支付失败',
									icon: 'none'
								});
							}
						});
					},
					fail: (res) => {
						console.log(res);
						uni.showToast({
							title: '支付失败',
							icon: 'none'
						});
					}
				});
				// #endif
			}
		},

		onLoad(options) {
			this.order_id = options.id;

			leaseReturnBill({
				id: this.order_id,
				action: 'info'
			}).then(res => {
				if (res.code != 1) return;
				const data = res.data;
				this.billInfo = data;
				this.goods = data.goods_info;

				switch (this.goods.periods_attribute) {
					case 'is_week':
						this.priceDayRent = (this.goods.issue_rent / 7).toString().match(/^\d+(?:\.\d{0,2})?/);
						break;
					case 'is_month':
						this.priceDayRent = (this.goods.issue_rent / 30).toString().match(/^\d+(?:\.\d{0,2})?/);
						break;
				}

				let payable = 0;
				let lateFee = 0;
				let totalRent = 0;

				data.lists.forEach(item => {
					lateFee += item.late_fee * 1;
					payable += item.amount_payable * 1;
					totalRent += item.late_fee * 1 + item.amount_payable * 1;
				})

				this.pricePayable = payable.toString().match(/^\d+(?:\.\d{0,2})?/) * 1;
				this.priceLateFee = lateFee.toString().match(/^\d+(?:\.\d{0,2})?/) * 1;
				this.priceTotalRent = (totalRent + data.falsify_price * 1).toString().match(/^\d+(?:\.\d{0,2})?/) * 1;
			});

			// 获取付款方式
			payment().then(res => {
				if (res.code != 1) return;
				const data = res.data;
				this.paywayList = data;
				this.payway = data.length ? data[0].pay_way : 0
			});
		}
	}
</script>


<style scoped>
	.container {
		padding: 20rpx;
		border-radius: 7px;
		background-color: #FFFFFF;
	}

	.lease-goods-return {
		padding: 20rpx;
	}

	.price-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 20rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.price-total {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 94rpx;
		border-top: 1px solid #E5E5E5;
		color: #333333;
	}

	.price-total-title {
		font-size: 28rpx;
	}

	.price-total-count {
		font-size: 36rpx;
	}


	.payway-title {
		font-size: 26rpx;
		color: #666666;
	}
	
	.payway-content {
		display: flex;
		flex-direction: column;
		width: 100%;
	}

	.payway-item {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 20rpx 0;
	}

	.payway-item:nth-child(n+2) {
		border-top: 1px dashed #E5E5E5;
	}

	.payway-name {
		font-size: 28rpx;
		color: #101010;
	}

	.payway-extra {
		font-size: 24rpx;
		color: #999999;
	}

	.payway-radio {
		/* margin-left: auto; */
	}

	.fixed {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		padding: 20rpx;
	}

	.button--submit {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 100%;
		height: 84rpx;
		font-size: 32rpx;
		border-radius: 50px;
		background-color: #24A3FF;
		color: #FFFFFF;
	}

	.desc-container {
		padding: 20rpx 40rpx;
		font-size: 28rpx;
		color: #333333;
	}

	.desc-title {
		font-weight: 500;
		margin-right: 10rpx;
	}
</style>
